<?php

namespace app\modules\indexapi\controllers;

use app\models\Product;
use app\models\Sku;

class SkuController extends BaseController
{
    public function actionInfo()
    {
        $product_id = \Yii::$app->request->post('product_id');
        $product = Product::findOne($product_id);
        $skuCount = Sku::find()->where(['=', 'product_id', $product_id])->count();

        $data = [
            'product_id' => $product_id,
            'sku_id' => 0,
            'stock_num' => 0,
            'price' => 0,
            'canSale' => 0
        ];

        if ($skuCount) {
            $attr_data = \Yii::$app->request->post('attr_data');
            if ($attr_data) {
                $sku = Sku::find()->where(['JSON EQ', 'attr_data', $attr_data])
                    ->andWhere(['=', 'product_id', $product_id])
                    ->one();
                if ($sku) {
                    return array_merge($data, [
                        'sku_id' => $sku->id,
                        'stock_num' => $sku->stock_num,
                        'price' => $sku->price,
                        'canSale' => 1
                    ]);
                }
            }

            return $data;
        }

        return array_merge($data, [
            'stock_num' => $product->stock_num,
            'price' => $product->price,
            'canSale' => 1,
        ]);
    }
}
